package com.it.system.user.handler;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.it.system.educommonapi.entity.User;
import com.it.system.educommonapi.entity.UserVO;
import com.it.system.educommonapi.util.JwtUtils;
import com.it.system.educommonapi.util.RsaUtils;
import com.it.system.user.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;

import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * 登录成功的处理
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获得登录的用户信息 userdetails.User
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
        //查询用户登录信息
        User user1 = userService.getOne(
                new QueryWrapper<User>().lambda().eq(User::getUsername, user.getUsername())
        );
        //转换JWT字符串
        String token = JwtUtils.generateToken(user1.getUsername(), RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
        UserVO userVO = new UserVO(user1, token);
        //发送数据到前端
        response.addHeader("Content-Type", "application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(ResponseEntity.ok(userVO)));


    }
}
